package net.njcp.mybatis.frame.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.stream.Stream;

/**
 * @ClassName ReflectUtil
 * @Description: TODO
 * @Author 柳拓
 * @Date 2019/9/25
 * @Version V1.0
 **/
public class ReflectUtil {

    /**
     * 首字母转小写
     * @param s
     * @return
     */
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    /**
     * 首字母转大写
     * @param s
     * @return
     */
    public static String toUpperCaseFirstOne(String s){
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    /**
     * 获取字段的范型类
     * @param nameField
     * @return
     */
    public static Class<?> getParadigm(Field nameField){
        Class<?> aClass = null;
        Type genericType = nameField.getGenericType();
        if(genericType instanceof ParameterizedType){
            ParameterizedType pt = (ParameterizedType) genericType;
            //得到泛型里的class类型对象
            aClass = (Class<?>)pt.getActualTypeArguments()[0];
        }
        return aClass;
    }

    /**
     * 通过对象获取类名
     * @param object 对象实例
     * @return className
     */
    public static String getName(Object object){
        Class<?> clz = object.getClass();
        String packageAndName = clz.getName();
        return getName(packageAndName);
    }

    /**
     * 通过包名加类名获取类名部分,并将首字母小写，将中间大写字母转小写加上_
     * @param packageAndName 包名加类名 com.className
     * @return className
     */
    public static String getName(String packageAndName){
        String[] classArr = packageAndName.split("\\.");
        return MatchesUtil.switchParam(toLowerCaseFirstOne(classArr[classArr.length-1]));
    }

    /**
     * 实例化对象
     * @param cls
     * @return
     */
    public static Object getObject(Class cls){
        Object obj = null;
        try {
            obj = cls.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static String getPrimaryKey(Class entityClass){
        Field[] fields = entityClass.getDeclaredFields();
        return ((Field)((Stream.of(fields)
                .filter(field -> !Modifier.isStatic(field.getModifiers()))
                .filter(field -> !Modifier.isFinal(field.getModifiers()))
                .toArray())[0])).getName();
    }

}
